<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;
use think\facade\Db;
use app\api\model\Yjcomm;
/**
 *今日业绩
 * Class TimeModel
 * @package app\common\model
 */
class StoreDataModel extends Model
{
    public function __construct()
    {
        $this->Yjcomm=new Yjcomm();
    }
       //当前日期前30天日期列表
       public function getData30Days(){
        $days=[];
        for ($i=0; $i <=30; $i++) { 
            // $days[$i]=date("Y-m-d",strtotime('-'.$i.'day'));
            $day=date("Y-m-d",strtotime('-'.$i.'day'));
            $format=date("m-d",strtotime('-'.$i.'day'));
            $days[$i][$format]["first"] =$day." 00:00:00";
            $days[$i][$format]["last"] = $day." 23:59:59";
            
        }
        return $days;
    }
    public function get_week($date){
        $date_str=date('Y-m-d',strtotime($date));
        
        $arr=explode("-", $date_str);
        
        $year=$arr[0];
        
        $month=sprintf('%02d',$arr[1]);
        
        $day=sprintf('%02d',$arr[2]);
        
        $hour = $minute = $second = 0;
        
        $strap = mktime($hour,$minute,$second,$month,$day,$year);
        
        $number_wk=date("w",$strap);
        
        $weekArr=array("周日","周一","周二","周三","周四","周五","周六");
        
        return $weekArr[$number_wk];
        
        }
    /**
     * 获取最近七天所有日期
     */
    function get_weeks($time = '', $format='Y-m-d')
    {
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i=1; $i<=7; $i++) {
            // $date[$i] = date($format, strtotime('+' . $i-7 .' days', $time));
            $day=date($format, strtotime('+' . ($i-7) .' days', $time));
            $date[$i][$this->get_week($day)]["first"] =$day." 00:00:00";
            $date[$i][$this->get_week($day)]["last"] = $day." 23:59:59";
        }
        return $date;
    }
    //本月所有日期
    function get_day_num($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('d', $time);
        $date = [];
        for ($i=1; $i<=date('t'); $i++){
            // $date[$i-1] = date($format ,strtotime( '+' . $i-$week .' days', $time));
            $day= date($format ,strtotime( '+' . ($i-$week) .' days', $time));
            $tmp=date('d' ,strtotime( '+' . ($i-$week) .' days', $time));
            $date[$i-1][$tmp]["first"] =$day." 00:00:00";
            $date[$i-1][$tmp]["last"] = $day." 23:59:59";
        }
        return $date;
    }
    //获取当前月份往前的12个月份开始和结束时间
    public function getDateMouth(){
        $currentTime = time();
        $cyear = floor(date("Y",$currentTime));
        $cMonth = floor(date("m",$currentTime));
        $dataArray = [];
        $num = 0;
        for ($i=0;$i<12;$i++){
            $array = [];
            $nMonth = $cMonth-$i;
            $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
            if($nMonth == 0){
                $nMonth = 12;
            }
            if($nMonth < 0){
                $nMonth = 12;
                $num++;
                $nMonth = $nMonth-$num;
            }
            $date = $cyear.'-'.$nMonth;
            $firstday = date("Y-m-01",strtotime($date));
            $lastday = date("Y-m-t",strtotime($date));
            $array[$date]["first"] = $firstday;
            $array[$date]["last"] = $lastday;
            $dataArray[] = $array;
        }
        $newArr=[];
        for ($i = count($dataArray)-1;$i>=0;$i--) { 
            array_push($newArr,$dataArray[$i]);
        }
        //sort($dataArray);
        return $newArr;
    }
     /**
     * 获取指定时间订单金额和单数 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2021-07-28
     * @param [type] $date
     * @param [type] $store_id
     * @param [type] $type 1：金额  2：单数
     * @return void
     */
    public function getOrdersPriceNumber($date,$store_id,$type){
        
        $data=[];
     
        foreach($date as $k=>$v){
          
            foreach ($v as $kk => $vv) {
               
                $first=strtotime($vv['first']);
                $last=strtotime($vv['last']);
                $where=[
                    ['store_id','=',$store_id],
                    ['orders_status','not in', [0]],
                    ['orders_create_time','between',"$first,$last"]
                ];
                $card_ids=Db::name('card')->where('store_id',$store_id)->column('id');
                $wherecard=[
                    ['is_pay','=',1],
                    ['create_time','between',[$first,$last]],
                    ['card_id','in',$card_ids],
                ];
               
                if($type==1){
                    $orders_id=Db::name('orders')-> where($where) -> column('orders_id');
                    $amount= Db::name('orders_server')->whereIn('orders_id',$orders_id) -> sum('act_price');
                    $package_card=Db::name('package_card')->where($wherecard)->sum('amount');
                    $amount=$amount+$package_card;
                }else{
                    $amount= Db::name('orders')-> where($where) -> count();
                    $package_card=Db::name('package_card')->where($wherecard)->count();
                    $amount=$amount+$package_card;
                   
                }
                array_push($data,$amount);
            }
         }
      
        return $data;
    }
     //首页订单金额和订单数
     public function getAchievement(){
        $store=db('store')->whereIn('store_id',[594,604,607,608])->field('store_name,store_id')->order('store_id asc')->select();
        $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
        $EndDate=date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
        $start_time=date('Y-m-d 00:00:00',time());
        $end_time=date('Y-m-d 23:59:59',time());
        $yesterday_start_time=date("Y-m-d 00:00:00",strtotime("-1 day"));
        $yesterday_end_time=date("Y-m-d 23:59:59",strtotime("-1 day"));
        foreach ($store as $k => $v) {
      
            $store[$k]["store_name"]     =$v['store_name'];
        
            $day=$this->getDataOrders($v['store_id'],strtotime($start_time),strtotime($end_time));
            $month=$this->getDataOrders($v['store_id'],strtotime($BeginDate),strtotime($EndDate));
            $yesterday=$this->getDataOrders($v['store_id'],strtotime($yesterday_start_time),strtotime($yesterday_end_time));
            $store[$k]['today_amount']       =$day['amount'];
            $store[$k]['month_amount']       =$month['amount'];
            $store[$k]['order__today_number']=$day['num'];
            $store[$k]['order__month_number']=$month['num'];
            $amount_scale=$yesterday['amount']>0?($day['amount']-$yesterday['amount'])/$yesterday['amount']*100:$day['amount'];
            $order_scale=$yesterday['num']>0?($day['num']-$yesterday['num'])/$yesterday['num']*100:$day['num'];
            $store[$k]['amount_scale']      =number_format( $amount_scale,2);
            $store[$k]['order_scale']       =number_format($order_scale,2);
        }
        response($store);
    }
    public function getDataOrders($store_id,$start_time,$end_time){
        $where['store_id']=$store_id;
        $where['orders_status']=['not in', [0]];
        $wh['store_id']=$store_id;
        $where['orders_close_time']=['between',"$start_time,$end_time"];
        $wh['order_write_off_time']=['between',"$start_time,$end_time"];
        $amount= db('orders')-> where($where) -> sum('amount');
        $num= db('orders_server')-> where($wh) -> count();
        return [
            'amount'=>$amount,
            'num'   =>$num
        ];
    }
}
